﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using InTheHand.Net.Sockets;
using Newtonsoft.Json.Linq;
using WinHBM.Core.Bluetooth;
using WinHBM.Core.Net.Http;
using System.Windows.Forms;
using WinHBM.Core.DB;
using WinHBM.Utils;
using WinHBM.Core.module;

namespace WinHBM.Core.Net.Sockets.Cmd
{


    public delegate void GetFlower(JObject obj);
    public delegate void ChangeSizeWindow();

    public class BluetoothOnlineCmd : SocketCmd
    {
        FlashSocketServer socket;
        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(BluetoothDataCmd));
        private HttpClient client = HttpClient.Instance;

        public override void executeCmd(JObject request, FlashSocketServer socket)
        {
            if (BluetoothClientHolder.bluetoothClient == null)
            {
                socket.Send(wrapCmd(CMD_BLUETOOTH_ONLINE, "未连接"));
                return;
            }
            try
            {
                this.socket = socket;
                MagicBar bar = BluetoothClientHolder.magicBar;
                bar.OnFlowerData += Bar_OnFlowerData;
                bar.OnLostConnection += Bar_OnLostConnection;
                bar.Online();
                BluetoothClientHolder.Online = true;
            }
            catch (Exception e)
            {
                Logger.Error(e);
                socket.Send(wrapCmd(CMD_BLUETOOTH_ONLINE,e.Message));
            }
        }

        private void Bar_OnLostConnection()
        {

            //socket发送丢失连接指令
            socket.Send(wrapCmd(CMD_BLUETOOTH_ONLINE, CMD_BLUETOOTH_ONLINE_CONNECTFAILED));
            //BluetoothClientHolder.magicBar = null;
            //BluetoothClientHolder.bluetoothClient = null;
            string address = BluetoothClientHolder.Address; 
            BluetoothManager manager = new BluetoothManager();
            while(true)
            {
                Thread.Sleep(1000);
                if (!BluetoothClientHolder.Online)//用户已经操作离线了，不需要重连
                {
                    Console.WriteLine("用户已经操作离线了，不需要重连1");
                    break;
                }
                try
                {
                    BluetoothClient client = manager.Connect(address);
                    client.Close();
                    Thread.Sleep(1000);
                    client = manager.Connect(address);
                    if (client != null)
                    {
                        if (!BluetoothClientHolder.Online)//用户已经操作离线了，不需要重连
                        {
                            Console.WriteLine("用户已经操作离线了，不需要重连2");
                            client.Close();
                            break;
                        }
                        //重新创建一个bar实例，恢复蓝牙连接
                        MagicBar bar = new MagicBar(client);
                        bar.CMD_GetNowTime();
                        bar.OnFlowerData += Bar_OnFlowerData;
                        bar.OnLostConnection += Bar_OnLostConnection;
                        bar.Online();
                        BluetoothClientHolder.bluetoothClient = client;
                        BluetoothClientHolder.magicBar = bar;
                        //socket 发送重新连接成功指令
                        socket.Send(wrapCmd(CMD_BLUETOOTH_ONLINE, CMD_BLUETOOTH_ONLINE_CONNECTSUCCESS)); 
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
        private void Bar_OnFlowerData(RedFlower flower)
        {
            try
            {
                JObject obj = new JObject();
                obj["sender_user_role_id"] = flower.teacherId;
                obj["baby_id"] = flower.studentId;
                obj["flower_time"] = flower.year + "-" + flower.month + "-" + flower.day + " " + flower.hour + ":" + flower.minute + ":" + flower.second;

                if (flower.type == FlowerType.Red)
                {
                    obj["type"] = "0";
                }
                else if (flower.type == FlowerType.Gold)
                {
                    obj["type"] = "1";
    
                }
                Logger.Debug(obj.ToString());
                //数据库保存红花记录
                UtilFlower.localSave(flower);

                //验证数据库是否有这个学生
                if (!Baby.hasBaby(flower.studentId))
                {
                    Logger.Debug("宝宝 " + flower.studentId + " 不存在");
                    return;
                }
                GetFlower getFlower = OnMain;
                MainForm.INSTANCE.Invoke(getFlower,new object[] { obj });
            }
            catch (Exception e)
            {
                Logger.Error(e);
                socket.Send(wrapCmd(CMD_BLUETOOTH_ONLINE, e.Message));
            }
        }



        private void MainFormMaxsize()
        {
            MainForm.INSTANCE.WindowState = FormWindowState.Maximized;
        }

        private void MainFormMinsize()
        {
            MainForm.INSTANCE.WindowState = FormWindowState.Minimized;
        }


        private void OnMain(JObject obj)
        {
            MainForm.INSTANCE.TopMost = true;
            if (MainForm.INSTANCE.WindowState == FormWindowState.Minimized)
            {
                MainFormMaxsize();
                socket.Send(wrapCmd(CMD_BLUETOOTH_ONLINE, obj));
                System.Timers.Timer time = new System.Timers.Timer(8000);
                time.Elapsed += Time_Elapsed;
                time.Start();
            }
            else {
                socket.Send(wrapCmd(CMD_BLUETOOTH_ONLINE, obj));
            }
            
        }

        private void Time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            ((System.Timers.Timer)sender).Stop();
            ChangeSizeWindow minsize = MainFormMinsize;
            MainForm.INSTANCE.Invoke(minsize);
        }
    }
}
